<template>
  <el-container>
    <el-header>Header</el-header>
    <el-main style="background: #f2f2f2;">
      <el-main class="main">
        <!-- top -->
        <div class="top">
          <span
            style="font-family: '微软雅黑'; font-weight: 400; font-size: 13px;"
          >
            数据列表
          </span>
          <el-button @click="dialogVisible = true">添加</el-button>
        </div>
        <!-- 表格 -->
        <el-row style="padding-top: 20px;">
          <el-col :span="24">
            <el-table :data="state.tableData" border style="width: 100%;">
              <el-table-column
                prop="departmentName"
                label="角色名称"
                align="center"
              />
              <el-table-column
                prop="adminNumber"
                label="成员数量"
                align="center"
              />
              <el-table-column
                prop="createTime"
                label="添加时间"
                align="center"
                :formatter="dateFormat"
              />
              <el-table-column
                prop="isDeleted_text"
                label="是否启用"
                align="center"
              />
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button
                    type="text"
                    @click="permission(scope.$index, scope.row.id)"
                  >
                    权限设置
                  </el-button>
                  <el-button
                    type="text"
                    @click="deleteRoleList(scope.$index, scope.row.id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <!-- 分页 -->
        <div>
          <el-row style="padding-top: 20px;">
            <el-col :span="24" class="pagination">
              <el-pagination
                :current-page="state.currentPage"
                :page-size="state.pageSize"
                layout="total, prev, pager, next"
                :total="state.total"
                @current-change="handleCurrentChange"
              />
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-main>
  </el-container>
  <!-- 新增 -->
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="确定新增"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :rules="rules"
        ref="ruleFormRef"
        label-width="120px"
        :model="addForm"
        status-icon
      >
        <el-form-item label="角色名称" prop="departmentName">
          <el-input
            v-model="addForm.departmentName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="des">
          <el-radio-group v-model="addForm.isDeleted" class="ml-4">
            <el-radio label="1" size="large">是</el-radio>
            <el-radio label="2" size="large">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="addForm.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addRole">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, FormRules, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { RoleManagement, addRoleManagement, deleteRole } from '../http/api'

onMounted(() => {
  getRoleList()
})
var state:any = reactive({
  tableData: [],
  currentPage: 1,
  pageSize: 4,
  page: 1,
  total: 3,
})
const addForm:any = reactive({
  name: '',
  des: '',
  isDeleted: '',
  adminNumber: 0,
})
const formInline = reactive({
  user: '',
  region: '',
})
var dialogVisible = ref(false)

const handleCurrentChange = (val: number) => {
  state.currentPage = val
  getRoleList()
}
const rules = reactive<FormRules>({
  departmentName: {
    required: true,
    message: '不能为空',
    trigger: 'blur',
  },
  description: {
    required: true,
    message: '不能为空',
    trigger: 'blur',
  },
})

const router: any = useRouter()
const route = useRouter()
const permission: any = (index, id) => {
  router.push({ path: 'permission', query: { id: id } })
}
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
//获取列表
const getRoleList: any = () => {
  RoleManagement({ page: state.currentPage, limit: state.pageSize }).then(
    (res:any) => {
      console.log(res.data)
      state.tableData = res.data
      state.total = res.count
      state.page = Math.ceil(res.count / state.pageSize)
      state.tableData.forEach((item: any) => {
        item.isDeleted === '0'
          ? (item.isDeleted_text = '禁用')
          : (item.isDeleted_text = '启用')
      })
    },
  )
}
//新增
function addRole() {
  addRoleManagement(addForm).then((res) => {
    console.log(res)
    console.log(addForm)
    if (res.data.code === 50000) {
      ElMessage({
        message: res.data.msg,
        type: 'warning',
      })
    } else {
      getRoleList()
      ElMessage({
        message: res.data.msg,
        type: 'success',
      })
    }
  })
}
//删除
function deleteRoleList(index, id) {
  ElMessageBox.confirm(
    '确定要删除吗？删除后该部门的管理员也会被删除',
    '谨慎操作！！！',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      deleteRole(id).then((res) => {
        if (res.data.code === 0) {
          getRoleList()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '操作取消',
      })
    })
}
//转换时间
const dateFormat = (row, column) => {
  var date = new Date(row.createTime)
  var year = date.getFullYear()
  var month =
    date.getMonth() < 9
      ? '0' + (date.getMonth() + 1)
      : '' + (date.getMonth() + 1)
  var day = date.getDate() < 10 ? '0' + date.getDate() : '' + date.getDate()
  var hour = date.getHours() < 10 ? '0' + date.getHours() : '' + date.getHours()
  var minutes =
    date.getMinutes() < 10 ? '0' + date.getMinutes() : '' + date.getMinutes()
  var seconds =
    date.getSeconds() < 10 ? '0' + date.getSeconds() : '' + date.getSeconds()
  return (
    year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
  )
}
</script>

<style scoped>
.main {
  background-color: white;
  border-radius: 10px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
.top {
  display: flex;
  justify-content: space-between;
}
</style>
